const webpack = require('webpack')
const path = require('path')

const HtmlWebpackPlugin = require('html-webpack-plugin')
const VueLoaderPlugin = require('vue-loader/lib/plugin')

const StylelintPlugin = require('stylelint-webpack-plugin')

const MiniCssExtractPlugin = require('mini-css-extract-plugin')

module.exports = (env) => {
  
  // 由于开发环境没必要对提取 css 到单个文件，
  // 所以这里判断下，当 env === 'prod' 才使用 MiniCssExtractPlugin.loader
  const cssLoader = [
    env === 'prod' ? MiniCssExtractPlugin.loader : 'style-loader',
    'css-loader',
    'postcss-loader',
  ]

  const config = {
    mode: 'none',
    entry: './src/main.js',
    output: {
      path: path.join(__dirname, 'dist'),
      filename: '[name].js'
    },
    module: {
      rules: [{
        test: /\.js$/,
        exclude: /node_modules/,
        use: [
          'babel-loader'
        ]
      }, {
        test: /\.vue$/,
        use: [
          'vue-loader'
        ]
      }, {
        test: /\.(js|vue)$/,
        exclude: /node_modules/,
        use: [
          'eslint-loader'
        ],
        enforce: 'pre'
      }, {
        test: /\.less$/,
        use: [
          ...cssLoader,
          'less-loader'
        ]
      }, {
        test: /\.css$/,
        use: [
          ...cssLoader
        ]
      }, {
        test: /\.(png|jpg|jpeg|git)$/,
        use: {
          loader: 'url-loader',
          options: {
            limit: 10 * 1024, // 10KB; 超出后会自动使用 file-loader
            esModule: false, // 不使用 ESM 的异步加载
          }
        }
      }]
    },
    plugins: [
      new webpack.DefinePlugin({
        BASE_URL: '"./"'
      }),
      new HtmlWebpackPlugin({
        template: './public/index.html',
        title: 'fed-e-task-02-02'
      }),

      new VueLoaderPlugin(),

      new StylelintPlugin({
        files: ['src/**.{vue,html,css,less}'], // 要检验的文件
        cache: false, // 不保存上次 stylelint 的检查结果
        emitError: true, // 返回错误信息
      }),
    ],
    resolve: {
      extensions: ['.js', '.json', '.vue']
    }
  }

  return config
}